package org.app.Service.Impl;

import jakarta.annotation.Resource;
import org.app.Entity.DTO.UserRoleDTO;
import org.app.Entity.Group;
import org.app.Entity.GroupUser;
import org.app.Entity.User;
import org.app.Entity.comm.Result;
import org.app.Mapper.IGroupMapper;
import org.app.Mapper.IUserMapper;
import org.app.Service.IGroupService;
import org.app.Utils.createGroupTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class GroupService implements IGroupService{
    @Resource
    private IGroupMapper groupMapper;
    @Resource
    private IUserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<Group> createExerciseGroup(Group group) {
        Result result = new Result();

        // 检查群组对象是否为空
        if (group == null) {
            result.setMessage("创建失败");
            result.setCode(500);
            result.setData(null);
            return result;
        }

        // 创建群组记录
        groupMapper.createExerciseGroup(group); // 这里假设 groupMapper 在插入后会填充 group_id
        //把用户填入群组用户表
        groupMapper.createExerciseGroupUser(group);

        // 生成并设置群组 Token
        Result<String> tokenResult = createGroupToken(group.getId());
        if (tokenResult.getCode() == 200) {
            group.setGroup_token(tokenResult.getData()); // 假设 Group 类有 group_token 属性
        } else {
            result.setMessage("创建失败：生成群组 Token 失败");
            result.setCode(500);
            result.setData(null);
            return result;
        }

        // 返回成功结果
        result.setCode(200);
        result.setData(group);
        result.setMessage("创建成功");
        return result;
    }

    @Override
    public Result<Group> createGuideGroup(Group group) {
        Result result = new Result();

        // 检查群组对象是否为空
        if (group == null) {
            result.setMessage("创建失败");
            result.setCode(500);
            result.setData(null);
            return result;
        }

        // 创建群组记录
        groupMapper.createGuideGroup(group); // 假设 groupMapper.createGuideGroup 插入后会填充 group_id
        //把用户填入群组用户表
        groupMapper.createGuideGroupUser(group);

        // 生成并设置群组 Token
        Result<String> tokenResult = createGroupToken(group.getId());
        if (tokenResult.getCode() == 200) {
            group.setGroup_token(tokenResult.getData()); // 假设 Group 类有 group_token 属性
        } else {
            result.setMessage("创建失败：生成群组 Token 失败");
            result.setCode(500);
            result.setData(null);
            return result;
        }

        // 返回成功结果
        result.setCode(200);
        result.setData(group);
        result.setMessage("创建成功");
        return result;
    }
    @Override
    public Result<Integer> updateAuth(GroupUser groupUser){
        Result result = new Result();
        if(groupUser.equals(null)){
            result.setMessage("授权失败");
            result.setCode(500);
            result.setData(null);
            return result;
        }else {
            result.setCode(200);
            result.setData(groupMapper.updateAuth(groupUser));
            result.setMessage("授权成功");
            return result;
        }
    }
    @Override
    public Result<Group> getGroupInfo(String group_id){
        Result result = new Result();
        Group group = groupMapper.selectById(group_id);
        if(group == null){
            result.setCode(500);
            result.setData(null);
            result.setMessage("没有找到该群");

        }else {
            result.setCode(200);
            result.setData(group);
            result.setMessage("已找到");
        }
        return result;
    }
    @Override
    public Result<String> createGroupToken(String group_id){
        String password;
        // 定义一个标志位，控制是否生成新密码
        boolean isUnique;
        do {
            // 生成新的口令
            password = createGroupTokenUtil.generatePassword();

            // 通过 password 直接从 Redis 查询是否已存在该密码
            String existingGroupId = (String) redisTemplate.opsForValue().get(password);

            // 如果未找到与该密码对应的 group_id，表示该密码是唯一的
            isUnique = (existingGroupId == null);

        } while (!isUnique); // 如果不是唯一的，重新生成密码


        /// 在 Redis 的 "group_tokens" Hash 中存储 group_id 和 token 映射
        redisTemplate.opsForHash().put("group_tokens", group_id, password);
        redisTemplate.opsForHash().put("token_groups", password, group_id);

        Group group = groupMapper.selectById(group_id);
        group.setGroup_token(password);
        groupMapper.updateById(group);

        Result result = new Result();
        result.setCode(200);
        result.setData(password);
        return result;
    }
    @Override
    public Result<Group> getGroupInfoByToken(String token) {
        String groupId = (String) redisTemplate.opsForHash().get("token_groups", token);
        if (groupId == null) {
            return new Result<>(500, "群口令错误", null);
        }
        Group group = groupMapper.selectById(groupId);
        if (group == null) {
            return new Result<>(500, "群组不存在", null);
        }
        return new Result<>(200, "查询成功", group);
    }
    @Override
    public Result<Integer> joinGroup(String group_id,String c_id){
        if(group_id == null){
            return new Result<>(500,"群口令错误",0);
        }
        //判断群成员数量是否满员
        Group group = groupMapper.selectById(group_id);
        if(group.getGroup_type() == 1){
            if(group.getMember_num() == 31){
                return new Result<>(500,"该教学指导群已经满员了",0);
            }
        }else if(group.getGroup_type() == 2){
            if(group.getMember_num() == 21){
                return new Result<>(500,"该训练指导群已经满员了",0);
            }
        }
        //没满，则修改群成员数量
        Integer member_num = group.getMember_num();
        group.setMember_num(member_num + 1);
        groupMapper.updateMemberNum(group);

        String c_nickname = userMapper.selectById(c_id).getC_name();
        GroupUser groupUser = new GroupUser();
        groupUser.setGroup_id(group_id);
        groupUser.setC_id(c_id);
        groupUser.setC_nickname(c_nickname);
        groupUser.setRole_id(1);
        groupMapper.joinGroup(groupUser);
        return new Result<>(200,"加入成功",1);

    }
    @Override
    public Result<List<Group>> listOwnGroup(String c_id){
        Result result = new Result();
        List<Group> groupList = groupMapper.listOwnGroup(c_id);
        result.setCode(200);
        result.setData(groupList);
        result.setMessage("查询成功");
        return result;
    }
    @Override
    public Result<List<Group>> listJoinGroup(String c_id){
        Result result = new Result();
        List<Group> groupList = groupMapper.listJoinGroup(c_id);
        result.setCode(200);
        result.setData(groupList);
        result.setMessage("查询成功");
        return result;
    }
    @Override
    public Result<Integer> deleteGroup(String group_id){
        Result result = new Result();
        Group group = groupMapper.selectById(group_id);
        List<String> ids = groupMapper.getAllMemberIds(group_id);
        //删除群里的全部成员
        for (String id : ids) {
            GroupUser groupUser = new GroupUser();
            groupUser.setGroup_id(group_id);
            groupUser.setC_id(id);
            groupMapper.deleteMember(groupUser);
        }
        //是否出错
        if(group == null){
            result.setCode(500);
            result.setMessage("未能找到群组");
            result.setData(null);
        } else {
            result.setCode(200);
            result.setData(groupMapper.deleteGroup(group));
            result.setMessage("删除成功");
        }
        return result;
    }
    @Override
    public Result<Integer> deleteMember(GroupUser groupUser){
        String group_id = groupUser.getGroup_id();

        //修改群成员数量
        Group group = groupMapper.selectById(group_id);
        Integer member_num = group.getMember_num();
        group.setMember_num(member_num-1);
        groupMapper.updateMemberNum(group);

        Result result = new Result();
        result.setCode(200);
        result.setData(groupMapper.deleteMember(groupUser));
        result.setMessage("已删除该成员");
        return result;
    }
    @Override
    public Result<Integer> updateNickName(GroupUser groupUser){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("修改成功");
        result.setData(groupMapper.updateNickName(groupUser));
        return result;
    }
    @Override
    public Result<List<UserRoleDTO>> listAllMembers(String group_id){
        List<GroupUser> memberList = groupMapper.getAllMembers(group_id);
        List<UserRoleDTO> userRoleDTOList = new ArrayList<>();
        for (GroupUser member : memberList) {
            User user = userMapper.selectById(member.getC_id());
            UserRoleDTO userRoleDTO = new UserRoleDTO(user,member);
            userRoleDTOList.add(userRoleDTO);
        }
        Result result = new Result();
        result.setCode(200);
        result.setData(userRoleDTOList);
        result.setMessage("查询成功");
        return result;
    }
    @Override
    public Result<UserRoleDTO> listMemberInfo(String group_id,String c_id){
        GroupUser groupUser = groupMapper.getGroupUser(group_id,c_id);
        User user = userMapper.selectById(c_id);
        UserRoleDTO userRoleDTO = new UserRoleDTO(user,groupUser);
        Result result = new Result();
        result.setCode(200);
        result.setData(userRoleDTO);
        result.setMessage("查找成功");
        return result;
    }
}